<template>
  <div class="view-container">
    <div class="content-container"></div>
    <div class="item-container" :style="{ transform: 'translateY(' + scrollTop + 'px)'}">
      <div class="item" v-for="i in newData">{{i}}</div>
    </div>
  </div>
</template>


<script setup lang="ts">
import {onMounted,ref} from "vue";

const data = new Array(5000).fill(0).map((_, i) => i);

const scrollTop = ref(0); // 初始滚动距离


let newData = ref([])
onMounted(() => {
  document.querySelector('.view-container').addEventListener('scroll',e => {
    // 获取滚动距离
    scrollTop.value = (e.target as HTMLElement).scrollTop;
    // 初始索引 = 滚动距离 / 每一项的高度
    const startIndex = Math.ceil(scrollTop.value / 40);
    // 结束索引 = 初始索引 + 容器高度 / 每一项的高度
    const endIndex = startIndex + 400 / 40;
    // 根据初始索引和结束索引，截取数据
    newData.value = data.slice(startIndex, endIndex)
  })
})
</script>



<style lang="less">
.view-container {
  height: 400px;
  width: 200px;
  border: 1px solid red;
  overflow-y: scroll;
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

.content-container {
  height: 20000px;
}

.item-container {
  position: absolute;
  top: 0;
  left: 0;
}

.item {
  height: 40px;
}

</style>
